/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
/**
 * Created by zhangyuantao on 2017/3/6.
 */

"use strict";

let path = require('path');
let fs = require('fs');
let { parseCSS2JSMap, parseMap } = require('@sxf/sf-theme');

const ASSETS_ROOT = path.resolve(__dirname, './dist');
const STATIC_DIRECTORY = 'theme';

const THEME_ROOT = path.resolve(__dirname, 'src/theme');

const THEME = fs.readdirSync(THEME_ROOT)
    .filter(file => !file.includes('core'))
    .filter(file => fs.statSync(path.resolve(THEME_ROOT, file)).isDirectory());

const SF_VUE_COMPONENT_THEME_MAP = {
    security: 'default'
};

module.exports = {
    version: '2.1',
    sourceMap: 'source-map',
    uglify: false,
    logLevel: 'DEBUG',

    // 打包时拷贝一些静态资源文件
    keepStructure () {
        return THEME.map(theme => {
            let srcTheme = SF_VUE_COMPONENT_THEME_MAP[theme] || theme;
            return {
                from: path.join(__dirname, `./node_modules/@sxf/sf-vue-component/dist/theme/${srcTheme}.css`),
                to: path.join(ASSETS_ROOT, `theme/sf-vue-components/${theme}.css`)
            };
        });
    },

    entry: THEME.reduce((prev, theme) => {
        prev[theme] = `./src/theme/${theme}/${theme}.pcss`;
        return prev;
    }, {}),

    staticDirectory: STATIC_DIRECTORY,
    relativePublicPath: true,
    resourceRelativePath: '../',
    resourceLimit: 10,
    autoRemoveStatic: false,
    postcss: true,
    output: {
        path: ASSETS_ROOT,
        publicPath: '/',
        filename: 'theme/[name].js',
        cssFilename: 'theme/[name].css',
        imgFilename: 'theme/images/[name].[hash:7].[ext]'
    },

    afterBuild () {
        let themeFolder = path.join(ASSETS_ROOT, 'theme');
        if (fs.existsSync(themeFolder)) {
            fs.readdirSync(themeFolder)
                .filter(file => !fs.statSync(path.resolve(themeFolder, file)).isDirectory())
                .filter(file => !/\.css(?:\.map)?$/.test(file))
                .forEach(file => fs.unlinkSync(path.resolve(themeFolder, file)));
        }

        THEME.forEach(theme => {
            let content = fs.readFileSync(path.join(__dirname, `src/theme/${theme}/${theme}.pcss`), {
                encoding: 'utf-8'
            });

            let themeBusiMap = parseCSS2JSMap(content);
            let themeColorMap = require(`@sxf/sf-theme/dist/${theme}.common.js`);
            let themeMap = Object.assign(themeBusiMap, themeColorMap);

            fs.writeFileSync(
                path.join(ASSETS_ROOT, `theme/${theme}.js`),
                'window.theme = ' + JSON.stringify(parseMap(themeMap)),
                {
                    encoding: 'utf-8'
                }
            );
        });
    }
};
